package com.pony.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pony.common.Result;
import com.pony.entity.Blog;
import com.pony.service.BlogService;
import com.pony.util.ShiroUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author pony
 * @since 2021-05-22
 */
@RestController
public class BlogController {

	@Resource
	BlogService blogService;

	@GetMapping("/blogs")
	public Result blogs(Integer currentPage) {
		if (currentPage == null || currentPage < 1) currentPage = 1;
		Page page = new Page(currentPage, 5);
		IPage pageData = blogService.page(page, new QueryWrapper<Blog>().orderByDesc("created"));
		return Result.success(pageData);
	}

	@GetMapping("/blog/{id}")
	public Result detail(@PathVariable(name = "id") Long id) {
		Blog blog = blogService.getById(id);
		Assert.notNull(blog, "该博客已删除！");
		return Result.success(blog);
	}

	@RequiresAuthentication
	@PostMapping("/blog/edit")
	public Result edit(@Validated @RequestBody Blog blog) {
		System.out.println(blog.toString());
		Blog temp = null;
		if (blog.getId() != null) {
			temp = blogService.getById(blog.getId());
			Assert.isTrue(temp.getUserId() == ShiroUtils.getProfile().getId(), "没有权限编辑");
		} else {
			temp = new Blog();
			temp.setUserId(ShiroUtils.getProfile().getId());
			temp.setCreated(LocalDateTime.now());
			temp.setStatus(0);
		}
		BeanUtil.copyProperties(blog, temp, "id", "userId", "created", "status");
		blogService.saveOrUpdate(temp);
		return Result.success("操作成功", null);
	}

}
